import { useContext, useEffect } from 'react';
import { useMemoizedFn } from 'ahooks';
import SocketContext from './context';
import type { EventHandler, ResultType } from '@/libs/socket/types';

export const useSocket = () => {
  const { socket } = useContext(SocketContext);
  return [socket];
}

type Options = {
  disabled?: boolean;
}

export const useListenMessage = (handler: EventHandler, options?: Options) => {
  const disabled = options?.disabled;

  const [socket] = useSocket();

  const listener = useMemoizedFn((data: ResultType) => {
    handler(data);
  });

  const removeListener = useMemoizedFn(() => {
    socket.off('message', listener);
  });

  useEffect(() => {
    if (!disabled) {
      socket.on('message', listener);
      return removeListener;
    }
  }, [socket, disabled]);

  return [removeListener];
}